Scroll Progress Bar

Strings

In C, a string is a sequence of characters stored in an array with a null terminator ('\0') at the end. Since C does not have a built-in string data type, strings are represented as character arrays. Each character in the string is stored in consecutive memory locations, and the null terminator marks the end of the string. To work with strings, C provides various standard library functions defined in string.h.

Usage and Syntax:

To declare and initialize a string in C, you can use a character array with enough size to hold the characters and the null terminator.

char string_name[] = "Hello, World!";
Sample Code with Explanation and Output:

#include <stdio.h>
#include <string.h>

int main() {
    // Declaration and initialization of a string
    char message[] = "Hello, World!";

    // Printing the entire string
    printf("Message: %s\n", message);

    // Finding the length of the string
    int length = strlen(message);
    printf("Length of the string: %d\n", length);

    // Accessing individual characters in the string
    printf("Characters: ");
    for (int i = 0; i < length; i++) {
        printf("%c ", message[i]);
    }
    printf("\n");

    // Modifying the string
    message[7] = 'M'; // Change 'W' to 'M'

    // Printing the modified string
    printf("Modified Message: %s\n", message);

    // Concatenating two strings
    char name[] = "John";
    char greeting[20];
    strcpy(greeting, "Hello, ");
    strcat(greeting, name);

    // Printing the concatenated string
    printf("Greeting: %s\n", greeting);

    return 0;
}
Output:

Message: Hello, World!
Length of the string: 13
Characters: H e l l o ,   W o r l d ! 
Modified Message: Hello, Morld!
Greeting: Hello, John
Explanation:
  • In the sample code, declare and initialize a string message with the value "Hello, World!".
  • Then use the %s format specifier to print the entire string.
  • Find the length of the string using the strlen() function and print it.
  • Using a loop, access and print each individual character in the string.
  • Next, modify the character at index 7 (changing 'W' to 'M') and print the modified string.
  • Then demonstrate concatenation by declaring another string name with the value "John". Initialize a new character array greeting and copy "Hello, " into it using strcpy(). Then concatenate the string name to greeting using strcat().
  • Finally, print the concatenated greeting.

What is a string in C?


Array

What character is used to terminate a string in C?


Null

What library should you include for string functions in C?


string.h

How do you compare two strings in C?


strcmp

What C function is used to find the length of a string?


strlen